<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
<meta name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">

    <meta name="author" content="WD">





<title>Machine Learning 学习笔记(四)——Matlab基础教程 | WD&#39;s blog</title>



    <link rel="icon" href="/favicon1.ico">




    <!-- stylesheets list from _config.yml -->
    
    <link rel="stylesheet" href="/css/style.css">
    



    <!-- scripts list from _config.yml -->
    
    <script src="/js/script.js"></script>
    
    <script src="/js/tocbot.min.js"></script>
    
    <script src="/js/snow.js"></script>
    



    
    
        
            <!-- MathJax配置，可通过单美元符号书写行内公式等 -->
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
    "HTML-CSS": {
        preferredFont: "TeX",
        availableFonts: ["STIX","TeX"],
        linebreaks: { automatic:true },
        EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
        inlineMath: [ ["$", "$"], ["\\(","\\)"] ],
        processEscapes: true,
        ignoreClass: "tex2jax_ignore|dno",
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
        equationNumbers: { autoNumber: "AMS" },
        noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" } },
        Macros: { href: "{}" }
    },
    messageStyle: "none"
    });
</script>
<!-- 给MathJax元素添加has-jax class -->
<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<!-- 通过连接CDN加载MathJax的js代码 -->
<script type="text/javascript" async
        src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML">
</script>


        
    


<meta name="generator" content="Hexo 5.4.0"></head>
<body>
    <div class="wrapper">
        <header>
    <nav class="navbar">
        <div class="container">
            <div class="navbar-header header-logo"><a href="/">WD&#39;s Blog</a></div>
            <div class="menu navbar-right">
                
                    <a class="menu-item" href="/archives">Posts</a>
                
                    <a class="menu-item" href="/category">Categories</a>
                
                    <a class="menu-item" href="/tag">Tags</a>
                
                    <a class="menu-item" href="/about">About</a>
                
                <input id="switch_default" type="checkbox" class="switch_default">
                <label for="switch_default" class="toggleBtn"></label>
            </div>
        </div>
    </nav>

    
    <nav class="navbar-mobile" id="nav-mobile">
        <div class="container">
            <div class="navbar-header">
                <div>
                    <a href="/">WD&#39;s Blog</a><a id="mobile-toggle-theme">·&nbsp;Light</a>
                </div>
                <div class="menu-toggle" onclick="mobileBtn()">&#9776; Menu</div>
            </div>
            <div class="menu" id="mobile-menu">
                
                    <a class="menu-item" href="/archives">Posts</a>
                
                    <a class="menu-item" href="/category">Categories</a>
                
                    <a class="menu-item" href="/tag">Tags</a>
                
                    <a class="menu-item" href="/about">About</a>
                
            </div>
        </div>
    </nav>

</header>
<script>
    var mobileBtn = function f() {
        var toggleMenu = document.getElementsByClassName("menu-toggle")[0];
        var mobileMenu = document.getElementById("mobile-menu");
        if(toggleMenu.classList.contains("active")){
           toggleMenu.classList.remove("active")
            mobileMenu.classList.remove("active")
        }else{
            toggleMenu.classList.add("active")
            mobileMenu.classList.add("active")
        }
    }
</script>
        <div class="main">
            <div class="container">
    
    
        <div class="post-toc">
    <div class="tocbot-list">
    </div>
    <div class="tocbot-list-menu">
        <a class="tocbot-toc-expand" onclick="expand_toc()">Expand all</a>
        <a onclick="go_top()">Back to top</a>
        <a onclick="go_bottom()">Go to bottom</a>
    </div>
</div>

<script>
    document.ready(
        function () {
            tocbot.init({
                tocSelector: '.tocbot-list',
                contentSelector: '.post-content',
                headingSelector: 'h1, h2, h3, h4, h5',
                collapseDepth: 1,
                orderedList: false,
                scrollSmooth: true,
            })
        }
    )

    function expand_toc() {
        var b = document.querySelector(".tocbot-toc-expand");
        tocbot.init({
            tocSelector: '.tocbot-list',
            contentSelector: '.post-content',
            headingSelector: 'h1, h2, h3, h4, h5',
            collapseDepth: 6,
            orderedList: false,
            scrollSmooth: true,
        });
        b.setAttribute("onclick", "collapse_toc()");
        b.innerHTML = "Collapse all"
    }

    function collapse_toc() {
        var b = document.querySelector(".tocbot-toc-expand");
        tocbot.init({
            tocSelector: '.tocbot-list',
            contentSelector: '.post-content',
            headingSelector: 'h1, h2, h3, h4, h5',
            collapseDepth: 1,
            orderedList: false,
            scrollSmooth: true,
        });
        b.setAttribute("onclick", "expand_toc()");
        b.innerHTML = "Expand all"
    }

    function go_top() {
        window.scrollTo(0, 0);
    }

    function go_bottom() {
        window.scrollTo(0, document.body.scrollHeight);
    }

</script>
    

    
    <article class="post-wrap">
        <header class="post-header">
            <h1 class="post-title">Machine Learning 学习笔记(四)——Matlab基础教程</h1>
            
                <div class="post-meta">
                    
                        Author: <a itemprop="author" rel="author" href="/about/">WD</a>
                     &nbsp;

                    
                        <span class="post-time">
                        Date: <a href="#">July 14, 2019&nbsp;&nbsp;17:27:27</a>
                        </span>
                     &nbsp;
                    
                        <span class="post-category">
                    Category:
                            
                                <a href="/categories/Machine-Learning/">Machine Learning</a>
                            
                        </span>
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <br>
    <span id="busuanzi_container_site_pv">总阅读量:<a href="#"><span id="busuanzi_value_page_pv"></span></a>次</span>&nbsp;
    <span class="post-count">文章字数:<a href="#">3.2k</span></a>&nbsp;
     <span class="post-count">阅读时长:<a href="#">15</span>min</a>
                    
                </div>
            
        </header>

        <div class="post-content">
            <h2 id="1-基本操作"><a href="#1-基本操作" class="headerlink" title="1.基本操作"></a>1.基本操作</h2><ul>
<li><p>计算数值</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; 5 + 6</span><br><span class="line">ans = 11</span><br><span class="line">&gt;&gt; 3 * 4</span><br><span class="line">ans = 12</span><br><span class="line">&gt;&gt; 1/3</span><br><span class="line">ans = 0.3333</span><br><span class="line">&gt;&gt; 2^6</span><br><span class="line">ans = 64</span><br></pre></td></tr></table></figure>
</li>
<li><p>计算逻辑值</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; 1 == 2</span><br><span class="line">ans = 0</span><br><span class="line">&gt;&gt; 1 ~= 2 </span><br><span class="line">ans = 1</span><br><span class="line">&gt;&gt; 1 &amp;&amp; 0</span><br><span class="line">ans = 0</span><br><span class="line">&gt;&gt; 1 || 0</span><br><span class="line">ans = 1</span><br></pre></td></tr></table></figure>
</li>
<li><p>变量</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; a = 6</span><br><span class="line">a = 6</span><br><span class="line">&gt;&gt; a = 6;  %加上分号可以使变量不打印输出</span><br><span class="line">&gt;&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>打印变量</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; a = pi;</span><br><span class="line">&gt;&gt; a       </span><br><span class="line">a = 3.1416</span><br><span class="line">&gt;&gt; disp(a)       %仅输出a的值</span><br><span class="line">    3.1416</span><br><span class="line">&gt;&gt; disp(sprintf(&quot;2 decimals : %0.2f&quot;,a))  %打印字符串（用c语言的格式）</span><br><span class="line">2 decimals : 3.14</span><br><span class="line">&gt;&gt; </span><br></pre></td></tr></table></figure>
</li>
<li><p>建立矩阵和向量</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; A = [1 2;3 4;5 6]  %分号代表矩阵的换行</span><br><span class="line">A =</span><br><span class="line">     1     2</span><br><span class="line">     3     4</span><br><span class="line">     5     6</span><br><span class="line">&gt;&gt; v = [1 2 3]     %表示行向量（1*3的矩阵）</span><br><span class="line">v =</span><br><span class="line">     1     2     3</span><br><span class="line">&gt;&gt; v = [1;2;3]     %表示列向量（3*1的矩阵）</span><br><span class="line">v =</span><br><span class="line">     1</span><br><span class="line">     2</span><br><span class="line">     3</span><br><span class="line">&gt;&gt; v = 1:0.1:2   %表示从1~2每隔0.1取数，得到的是一个行向量</span><br><span class="line">v =</span><br><span class="line">  1 至 8 列</span><br><span class="line">    1.0000    1.1000    1.2000    1.3000    1.4000    1.5000    1.6000    1.7000</span><br><span class="line">  9 至 11 列</span><br><span class="line">    1.8000    1.9000    2.0000</span><br><span class="line">&gt;&gt; v = 1:6       %当然也可以不取间隔</span><br><span class="line">v =</span><br><span class="line">     1     2     3     4     5     6</span><br></pre></td></tr></table></figure>
</li>
<li><p>用特殊方法建立矩阵</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; ones(2,3)   %建立2*3的矩阵，元素全部为1</span><br><span class="line">ans =</span><br><span class="line">     1     1     1</span><br><span class="line">     1     1     1</span><br><span class="line">&gt;&gt; 2*ones(2,3)    %用2*矩阵，元素全部为2</span><br><span class="line">ans =</span><br><span class="line">     2     2     2</span><br><span class="line">     2     2     2</span><br><span class="line">&gt;&gt; zeros(2,2)    %生成零矩阵</span><br><span class="line">ans =</span><br><span class="line">     0     0</span><br><span class="line">     0     0</span><br><span class="line">&gt;&gt; rand(1,3)    %生成0~1的随机矩阵</span><br><span class="line">ans =</span><br><span class="line">    0.8147    0.9058    0.1270</span><br><span class="line">&gt;&gt; randn(1,3)   %生成高斯分布矩阵（正态分布）均值为0，标准差为1</span><br><span class="line">ans =</span><br><span class="line">    0.8622    0.3188   -1.3077</span><br><span class="line">&gt;&gt; &gt;&gt; w = -6 + sqrt(10)*(randn(1,10000)); % 生成均值为-6，方差为10的10000个数据的矩阵</span><br><span class="line">&gt;&gt; hist(w)     %将这个矩阵用直方图的形式画出来</span><br><span class="line">&gt;&gt; hist(w,50)  %用50个竖条的直方图显示</span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20190714172205188.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTgxNTky,size_16,color_FFFFFF,t_70" alt=""></p>
</li>
</ul>
<p><img src="https://img-blog.csdnimg.cn/20190714172222619.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTgxNTky,size_16,color_FFFFFF,t_70" alt=""></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; eye(4)   %生成单位矩阵</span><br><span class="line">ans =</span><br><span class="line">     1     0     0     0</span><br><span class="line">     0     1     0     0</span><br><span class="line">     0     0     1     0</span><br><span class="line">     0     0     0     1</span><br><span class="line">&gt;&gt; eye(3)</span><br><span class="line">ans =</span><br><span class="line">     1     0     0</span><br><span class="line">     0     1     0</span><br><span class="line">     0     0     1</span><br></pre></td></tr></table></figure>
<h2 id="2-移动数据"><a href="#2-移动数据" class="headerlink" title="2.移动数据"></a>2.移动数据</h2><ul>
<li>矩阵的大小</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; A = [1 2;3 4;5 6]</span><br><span class="line">A =</span><br><span class="line">     1     2</span><br><span class="line">     3     4</span><br><span class="line">     5     6</span><br><span class="line">&gt;&gt; size(A)      %size()可以查看矩阵的大小</span><br><span class="line">ans =</span><br><span class="line">     3     2</span><br><span class="line">&gt;&gt; s = size(A)   </span><br><span class="line">s =</span><br><span class="line">     3     2</span><br><span class="line">&gt;&gt; size(s)        %size()本身返回的就是一个矩阵</span><br><span class="line">ans =</span><br><span class="line">     1     2</span><br><span class="line">&gt;&gt; size(A,1)     %将返回A矩阵第一维度的大小（行数）</span><br><span class="line">ans =</span><br><span class="line">     3</span><br><span class="line">&gt;&gt; size(A,2)     %将返回A矩阵第二维度的大小（列数）</span><br><span class="line">ans =</span><br><span class="line">     2</span><br><span class="line">&gt;&gt; v = [1 2 3 4]</span><br><span class="line">v =</span><br><span class="line">     1     2     3     4</span><br><span class="line">&gt;&gt; length(v)      %返回行向量的长度</span><br><span class="line">ans =</span><br><span class="line">     4</span><br><span class="line">&gt;&gt; length(A)   %返回较大的维度长度3</span><br><span class="line">ans =</span><br><span class="line">     3</span><br></pre></td></tr></table></figure>
<ul>
<li><p>加载文件中的数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; load(&#x27;ex1data1.txt&#x27;)   %使用load直接可以将文件中的数据读出来</span><br><span class="line">&gt;&gt; who           %显示当前工作区的变量</span><br><span class="line"></span><br><span class="line">您的变量为:</span><br><span class="line"></span><br><span class="line">A         ans       ex1data1  s         v         </span><br><span class="line"></span><br><span class="line">&gt;&gt; size(ex1data1)       %刚刚读的矩阵，查看长度</span><br><span class="line">ans =</span><br><span class="line">    97     2</span><br><span class="line">&gt;&gt; whos   %查看当前工作区变量的详细信息</span><br><span class="line">  Name           Size            Bytes  Class     Attributes</span><br><span class="line"></span><br><span class="line">  A              3x2                48  double              </span><br><span class="line">  ans            1x1                 8  double              </span><br><span class="line">  ex1data1      97x2              1552  double              </span><br><span class="line">  s              1x2                16  double              </span><br><span class="line">  v              1x4                32  double              </span><br><span class="line">&gt;&gt; clear(v)   %删除变量，不加指定则删除全部变量</span><br><span class="line">&gt;&gt; v = ex1data1(1:10)  %取前10个元素</span><br><span class="line">v =</span><br><span class="line">  1 至 8 列</span><br><span class="line">    6.1101    5.5277    8.5186    7.0032    5.8598    8.3829    7.4764    8.5781</span><br><span class="line">  9 至 10 列</span><br><span class="line">    6.4862    5.0546</span><br><span class="line">&gt;&gt; save v.mat v    %将v矩阵中的数据存到文件v.mat中去</span><br></pre></td></tr></table></figure>
<ul>
<li>这里存储文件时是以二进制格式存储的，因为数据量可能比较大，所以进行了压缩，如果想让人看懂存储的内容可使用下面的方法</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; save v.txt v -ascii</span><br></pre></td></tr></table></figure>
</li>
<li><p>操作矩阵中的数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; A</span><br><span class="line">A =</span><br><span class="line">     1     2</span><br><span class="line">     3     4</span><br><span class="line">     5     6</span><br><span class="line">&gt;&gt; A(3,2)  %取A矩阵中第三行第二列的元素</span><br><span class="line">ans =</span><br><span class="line">     6</span><br><span class="line">&gt;&gt; A(2,:)   %取A矩阵中第二行的所有元素</span><br><span class="line">ans =</span><br><span class="line">     3     4</span><br><span class="line">&gt;&gt; A(:,2)   %取第二列的所有元素</span><br><span class="line">ans =</span><br><span class="line">     2</span><br><span class="line">     4</span><br><span class="line">     6</span><br><span class="line">&gt;&gt; A([1 3],:)    %取A矩阵第一行和第三行的所有元素</span><br><span class="line">ans =</span><br><span class="line">     1     2</span><br><span class="line">     5     6</span><br><span class="line">&gt;&gt; A(:,2) = [10 15 20]  %取出元素之后其实可以对其进行赋值</span><br><span class="line">A =</span><br><span class="line">     1    10</span><br><span class="line">     3    15</span><br><span class="line">     5    20</span><br><span class="line">&gt;&gt; A = [A,[100;150;200]] %在A矩阵后面追加一列</span><br><span class="line">A =</span><br><span class="line">     1    10   100</span><br><span class="line">     3    15   150</span><br><span class="line">     5    20   200</span><br><span class="line">&gt;&gt; A(:)    %把A矩阵的所有元素放到一个列向量中</span><br><span class="line">ans =</span><br><span class="line">     1</span><br><span class="line">     3</span><br><span class="line">     5</span><br><span class="line">    10</span><br><span class="line">    15</span><br><span class="line">    20</span><br><span class="line">   100</span><br><span class="line">   150</span><br><span class="line">   200</span><br><span class="line">&gt;&gt; A = [1 2;3 4;5 6];</span><br><span class="line">&gt;&gt; B = [11 12;13 14;15 16];</span><br><span class="line">&gt;&gt; C = [A,B]     %将两个矩阵拼接到一起</span><br><span class="line">C =</span><br><span class="line">     1     2    11    12</span><br><span class="line">     3     4    13    14</span><br><span class="line">     5     6    15    16</span><br><span class="line">&gt;&gt; C = [A;B]      %分号表示换行，B矩阵放在A矩阵的下面</span><br><span class="line">C =</span><br><span class="line">     1     2</span><br><span class="line">     3     4</span><br><span class="line">     5     6</span><br><span class="line">    11    12</span><br><span class="line">    13    14</span><br><span class="line">    15    16</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="3-计算数据"><a href="#3-计算数据" class="headerlink" title="3.计算数据"></a>3.计算数据</h2><ul>
<li><p>矩阵之间的运算</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; A = [1 2;3 4;5 6];</span><br><span class="line">&gt;&gt; B = [11 12;13 14;15 16];</span><br><span class="line">&gt;&gt; C = [1 1;2 2]</span><br><span class="line">C =</span><br><span class="line">     1     1</span><br><span class="line">     2     2</span><br><span class="line">&gt;&gt; A * C     %A与C进行矩阵相乘</span><br><span class="line">ans =</span><br><span class="line">     5     5</span><br><span class="line">    11    11</span><br><span class="line">    17    17 </span><br><span class="line">&gt;&gt; A .* B      %&#x27;.*&#x27;代表矩阵中对应元素相乘</span><br><span class="line">ans =</span><br><span class="line">    11    24</span><br><span class="line">    39    56</span><br><span class="line">    75    96</span><br><span class="line">&gt;&gt; A .^ 2     %&#x27;.&#x27;代表对矩阵中的所有元素，乘方</span><br><span class="line">ans =</span><br><span class="line">     1     4</span><br><span class="line">     9    16</span><br><span class="line">    25    36</span><br><span class="line">&gt;&gt; v = [1 2 3] </span><br><span class="line">&gt;&gt; v = 1 ./ v    %取v矩阵的倒数</span><br><span class="line">v =</span><br><span class="line">    1.0000    0.5000    0.3333</span><br><span class="line">&gt;&gt; log(v)     %对v取log运算</span><br><span class="line">ans =</span><br><span class="line">         0   -0.6931   -1.0986</span><br><span class="line">&gt;&gt; exp(v)      %对v取e^v次方运算</span><br><span class="line">ans =</span><br><span class="line">    2.7183    1.6487    1.3956</span><br><span class="line">&gt;&gt; abs([-1;-2;3])  %对矩阵取绝对值运算</span><br><span class="line">ans =</span><br><span class="line">     1</span><br><span class="line">     2</span><br><span class="line">     3</span><br><span class="line">&gt;&gt; -v          %对矩阵取相反数</span><br><span class="line">ans =</span><br><span class="line">   -1.0000   -0.5000   -0.3333</span><br><span class="line">&gt;&gt; v = [1;2;3];</span><br><span class="line">&gt;&gt; v = v + ones(length(v),1) %将v中所有元素+1，先构造一个和v维度相同的矩阵（元素全为1），再把他们相加</span><br><span class="line">v =</span><br><span class="line">     2</span><br><span class="line">     3</span><br><span class="line">     4</span><br><span class="line">&gt;&gt; v = v +1     %实际上用+号就可以实现</span><br><span class="line">v =</span><br><span class="line">     3</span><br><span class="line">     4</span><br><span class="line">     5</span><br><span class="line">&gt;&gt; A&#x27;      %一个撇号是求矩阵的转置</span><br><span class="line">ans =</span><br><span class="line">     1     3     5</span><br><span class="line">     2     4     6</span><br></pre></td></tr></table></figure>
</li>
<li><p>对矩阵的函数操作</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; a = [-0.2 9.8 4.5 8 2.0]</span><br><span class="line">a =</span><br><span class="line">   -0.2000    9.8000    4.5000    8.0000    2.0000</span><br><span class="line">&gt;&gt; val = max(a)   %求矩阵的最大值</span><br><span class="line">val =</span><br><span class="line">    9.8000 </span><br><span class="line">&gt;&gt; [val index] = max(a)    %求矩阵的最大值并返回他的下标索引</span><br><span class="line">val =</span><br><span class="line">    9.8000</span><br><span class="line">index =</span><br><span class="line">     2</span><br><span class="line">&gt;&gt; a &lt; 3     %拿a中的所有元素和3比较返回结果</span><br><span class="line">ans =</span><br><span class="line">  1×5 logical 数组</span><br><span class="line">   1   0   0   0   1</span><br><span class="line">&gt;&gt; find(a&lt;3)   %返回满足条件的元素在a中的索引</span><br><span class="line">ans =</span><br><span class="line">     1     5</span><br><span class="line">&gt;&gt;A = magic(3)  %幻方矩阵，每一行每一列包括对角线元素之和相等</span><br><span class="line"> A =</span><br><span class="line">     8     1     6</span><br><span class="line">     3     5     7</span><br><span class="line">     4     9     2</span><br><span class="line">&gt;&gt; [r,c] = find(A&gt;=7)  %寻找A中大于等于7的元素索引，行和列</span><br><span class="line">r =</span><br><span class="line">     1</span><br><span class="line">     3</span><br><span class="line">     2</span><br><span class="line">c =</span><br><span class="line">     1</span><br><span class="line">     2</span><br><span class="line">     3</span><br><span class="line">&gt;&gt; sum(a)    %对矩阵中的元素求和</span><br><span class="line">ans =</span><br><span class="line">   24.1000</span><br><span class="line">&gt;&gt; prod(a)    %对矩阵中的元素相乘</span><br><span class="line">ans =</span><br><span class="line"> -141.1200</span><br><span class="line">&gt;&gt; floor(a)    %向下取整</span><br><span class="line">ans =</span><br><span class="line">    -1     9     4     8     2</span><br><span class="line">&gt;&gt; ceil(a)      %向上取整</span><br><span class="line">ans =</span><br><span class="line">     0    10     5     8     2</span><br><span class="line">&gt;&gt; A</span><br><span class="line">A =</span><br><span class="line">     8     1     6</span><br><span class="line">     3     5     7</span><br><span class="line">     4     9     2</span><br><span class="line">&gt;&gt; max(A,[],1)   %取每一列的最大值，1代表是第一维度</span><br><span class="line">ans =</span><br><span class="line">     8     9     7</span><br><span class="line">&gt;&gt; max(A,[],2)   %取每一行的最大值</span><br><span class="line">ans =</span><br><span class="line">     8</span><br><span class="line">     7</span><br><span class="line">     9</span><br><span class="line">&gt;&gt; max(max(A))  %取A矩阵所有元素的最大值</span><br><span class="line">ans =</span><br><span class="line">     9</span><br><span class="line">&gt;&gt; max(A(:))  %或者先将矩阵A转化为列向量，在取最大值</span><br><span class="line">ans =</span><br><span class="line">     9</span><br><span class="line">&gt;&gt; sum(A,1)  %求A每一列的和</span><br><span class="line">ans =</span><br><span class="line">    15    15    15</span><br><span class="line">&gt;&gt; sum(A,2) %求A每一行的和</span><br><span class="line">ans =</span><br><span class="line">    15</span><br><span class="line">    15</span><br><span class="line">    15</span><br><span class="line">&gt;&gt; A .* eye(3)   %将单位矩阵与A中的元素相乘得到对角线的元素</span><br><span class="line">ans =</span><br><span class="line">     8     0     0</span><br><span class="line">     0     5     0</span><br><span class="line">     0     0     2</span><br><span class="line">&gt;&gt; sum(sum(A .* eye(3)))  %求对角线元素的和</span><br><span class="line">ans =</span><br><span class="line">    15</span><br><span class="line">&gt;&gt; pinv(A)    %求逆矩阵</span><br><span class="line">ans =</span><br><span class="line">    0.1472   -0.1444    0.0639</span><br><span class="line">   -0.0611    0.0222    0.1056</span><br><span class="line">   -0.0194    0.1889   -0.1028</span><br><span class="line">&gt;&gt; temp = pinv(A);</span><br><span class="line">&gt;&gt; A*temp     %发现这就是单位矩阵</span><br><span class="line">ans =</span><br><span class="line">    1.0000   -0.0000    0.0000</span><br><span class="line">    0.0000    1.0000   -0.0000</span><br><span class="line">   -0.0000    0.0000    1.0000</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="4-数据绘制"><a href="#4-数据绘制" class="headerlink" title="4.数据绘制"></a>4.数据绘制</h2><ul>
<li><p>有时需要绘制数据的图像以便更好地观察我们的算法是否出现错误，或者更好的检验我们的想法的正确性，我们需要将数据可视化，这点很重要。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; t = [0:0.01:0.98]; </span><br><span class="line">&gt;&gt; y1 = sin(2*pi*4*t);</span><br><span class="line">&gt;&gt; plot(t,y1);   %用plot就可以画出对应的sin函数图像</span><br><span class="line">&gt;&gt; y2 = cos(2*pi*4*t);</span><br><span class="line">&gt;&gt; hold on;     %在同一界面上画图像</span><br><span class="line">&gt;&gt; plot(t,y2,&#x27;r&#x27;);   %画出cos的函数图像，用red</span><br><span class="line">&gt;&gt; xlabel(&#x27;time&#x27;);    %设置x轴坐标</span><br><span class="line">&gt;&gt; ylabel(&#x27;value&#x27;);   %设置y轴坐标</span><br><span class="line">&gt;&gt; legend(&#x27;sin&#x27;,&#x27;cos&#x27;);  %设置标识</span><br><span class="line">&gt;&gt; title(&#x27;my plot&#x27;);   %设置标题</span><br><span class="line">&gt;&gt; print -dpng &#x27;myplot.PNG&#x27;;  %将图像保存为PNG格式</span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20190714172306157.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTgxNTky,size_16,color_FFFFFF,t_70" alt=""></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; figure(1); plot(t,y1);  %对图像进行标号这样每个图象一个界面</span><br><span class="line">&gt;&gt; figure(2); plot(t,y2);</span><br><span class="line">&gt;&gt; subplot(1,2,1);    %将界面分为1*2的区域，用第一块区域</span><br><span class="line">&gt;&gt; plot(t,y1);     %第一块区域画y1的图像</span><br><span class="line">&gt;&gt; subplot(1,2,2);    %用第二块区域</span><br><span class="line">&gt;&gt; plot(t,y2);      %第二块区域画y2的图像</span><br><span class="line">&gt;&gt; axis([0.5 1 -1 1]);   %设置图像的横纵坐标范围</span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20190714172327178.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTgxNTky,size_16,color_FFFFFF,t_70" alt=""></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; A = magic(5)  %5*5的幻方矩阵</span><br><span class="line">A =</span><br><span class="line">    17    24     1     8    15</span><br><span class="line">    23     5     7    14    16</span><br><span class="line">     4     6    13    20    22</span><br><span class="line">    10    12    19    21     3</span><br><span class="line">    11    18    25     2     9</span><br><span class="line">&gt;&gt; imagesc(A);   %矩阵也可以可视化</span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20190714172348777.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTgxNTky,size_16,color_FFFFFF,t_70" alt=""></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; imagesc(A),colorbar,colormap gray; %执行了三个命令，用有灰度的图像来画矩阵，并显示灰度表</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20190714172416405.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTgxNTky,size_16,color_FFFFFF,t_70" alt=""></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; imagesc(magic(15)),colorbar,colormap gray;%打印15*15的幻方矩阵</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20190714172436744.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTgxNTky,size_16,color_FFFFFF,t_70" alt=""></p>
</li>
</ul>
<h2 id="5-控制语句：if，for，while语句"><a href="#5-控制语句：if，for，while语句" class="headerlink" title="5.控制语句：if，for，while语句"></a>5.控制语句：if，for，while语句</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; v = zeros(10,1)</span><br><span class="line">&gt;&gt; for i = 1:10,  %i = 1:10,之后把v(i)的值变为2的i次方</span><br><span class="line">     v(i) = 2^i;</span><br><span class="line">   end            %注意结束的时候加上end</span><br><span class="line">&gt;&gt; v</span><br><span class="line">v =</span><br><span class="line">           2</span><br><span class="line">           4</span><br><span class="line">           8</span><br><span class="line">          16</span><br><span class="line">          32</span><br><span class="line">          64</span><br><span class="line">         128</span><br><span class="line">         256</span><br><span class="line">         512</span><br><span class="line">        1024</span><br><span class="line">&gt;&gt; i = 1;</span><br><span class="line">&gt;&gt; while true,    %while循环</span><br><span class="line">     v(i) = 999;  %设置v(i)的值为999</span><br><span class="line">     i = i + 1;</span><br><span class="line">     if i == 6,  %当i=6时跳出循环</span><br><span class="line">        break;</span><br><span class="line">     end</span><br><span class="line">  end</span><br><span class="line">&gt;&gt; v</span><br><span class="line">v =</span><br><span class="line">         999</span><br><span class="line">         999</span><br><span class="line">         999</span><br><span class="line">         999</span><br><span class="line">         999</span><br><span class="line">          64</span><br><span class="line">         128</span><br><span class="line">         256</span><br><span class="line">         512</span><br><span class="line">        1024</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<ul>
<li><p>定义函数</p>
<p>创建一个sqrt_test.m文件，在里面输入以下内容：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">y</span> = <span class="title">sqrt_test</span><span class="params">(x)</span> %<span class="title">y</span>是返回值，<span class="title">x</span>为传入的参数</span></span><br><span class="line">    y = x^<span class="number">2</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>之后在控制台中cd 到文件所处目录，调这个函数执行命令</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; sqrt_test(<span class="number">5</span>);</span><br><span class="line">y =</span><br><span class="line">    <span class="number">25</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>matlab的函数还可以有多个返回值，比如将上面的函数改一下：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="params">[a,b]</span> = <span class="title">sqrt_test</span><span class="params">(x)</span></span></span><br><span class="line">    a = x^<span class="number">2</span></span><br><span class="line">    b = x^<span class="number">3</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; [a,b] = sqrt_test(5);</span><br><span class="line">a =</span><br><span class="line">    25</span><br><span class="line">b =</span><br><span class="line">   125</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
<li><p>下面用matlab实现代价函数的定义，并且用简单的数据集检验是否正确，数据集如下：</p>
<p><img src="https://img-blog.csdnimg.cn/20190714172501988.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTgxNTky,size_16,color_FFFFFF,t_70" alt=""></p>
<p>我们定义的代价函数如下：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">J</span> = <span class="title">costFunctionJ</span><span class="params">(X,y,theta)</span></span></span><br><span class="line">    m = <span class="built_in">size</span>(X,<span class="number">1</span>);       <span class="comment">%数据集的个数</span></span><br><span class="line">    predictions = X*theta;    <span class="comment">%假设函数预测的结果矩阵</span></span><br><span class="line">    sqrErrors = (predictions - y) .^ <span class="number">2</span>;   <span class="comment">%与实际值得误差</span></span><br><span class="line">    J = <span class="number">1</span>/(<span class="number">2</span>*m) * sum(sqrErrors);     <span class="comment">%计算代价函数</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>下面我们在终端中调用这个函数：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; X = [<span class="number">1</span> <span class="number">1</span>;<span class="number">1</span> <span class="number">2</span>;<span class="number">1</span> <span class="number">3</span>];</span><br><span class="line">&gt;&gt; Y = [<span class="number">1</span>;<span class="number">2</span>;<span class="number">3</span>];</span><br><span class="line">&gt;&gt; X</span><br><span class="line">X =</span><br><span class="line">     <span class="number">1</span>     <span class="number">1</span></span><br><span class="line">     <span class="number">1</span>     <span class="number">2</span></span><br><span class="line">     <span class="number">1</span>     <span class="number">3</span></span><br><span class="line">&gt;&gt; Y</span><br><span class="line">Y =</span><br><span class="line">     <span class="number">1</span></span><br><span class="line">     <span class="number">2</span></span><br><span class="line">     <span class="number">3</span></span><br><span class="line">&gt;&gt; theta = [<span class="number">0</span>;<span class="number">1</span>]</span><br><span class="line">theta =</span><br><span class="line">     <span class="number">0</span></span><br><span class="line">     <span class="number">1</span></span><br><span class="line">&gt;&gt; costFunctionJ(X,Y,theta)  <span class="comment">%theta0=0,theta0=1刚好拟合，故代价函数为0</span></span><br><span class="line"><span class="built_in">ans</span> =</span><br><span class="line">     <span class="number">0</span></span><br><span class="line">&gt;&gt; theta = [<span class="number">0</span>;<span class="number">0</span>]</span><br><span class="line">theta =</span><br><span class="line">     <span class="number">0</span></span><br><span class="line">     <span class="number">0</span></span><br><span class="line">&gt;&gt; costFunctionJ(X,Y,theta)</span><br><span class="line"><span class="built_in">ans</span> =</span><br><span class="line">    <span class="number">2.3333</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="6-向量化"><a href="#6-向量化" class="headerlink" title="6.向量化"></a>6.向量化</h2><ul>
<li><p>下面通过几个例子来说明向量化的代码会更加简单明了。</p>
</li>
<li><p>首先我们先写一个计算假设函数的function，前面我们已经知道假设函数的公式如下：</p>
<script type="math/tex; mode=display">
h(x) = \sum_{j=1}^{n}{\theta_jx_j}</script><p>那么正常来写求假设函数的matlab代码就是：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pre</span> = <span class="title">prediction</span><span class="params">(X,theta)</span></span></span><br><span class="line">    pre = <span class="number">0.0</span>;</span><br><span class="line">    n = <span class="built_in">size</span>(X,<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">for</span> <span class="built_in">j</span> = <span class="number">1</span>:n,</span><br><span class="line">        pre = pre + theta(<span class="built_in">j</span>) * X(<span class="built_in">j</span>)</span><br><span class="line">    <span class="keyword">end</span>;</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>而我么前面也推到过，假设函数还可以写成向量的形式：</p>
<script type="math/tex; mode=display">
h(x)=\theta_0+\theta_1x_1+\theta_2x_2+···+\theta_nx_n=[\theta_0,\theta_1,···\theta_n] * \left[\begin{array}{cc\r}x_0 \\x_1\\x_2\\···\\x_n \end{array}\right] \\=\theta^TX</script><p>这样我们的函数就可以使用matlab提供的线性代数库来求解了，可以大大减少代码量：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pre</span> = <span class="title">prediction</span><span class="params">(X,theta)</span></span></span><br><span class="line">   pre = theta&#x27; * X;  <span class="comment">% &#x27; 代表矩阵的转置</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
<li><p>再比如说我们前面所讨论的的梯度下降的更新公式：</p>
<script type="math/tex; mode=display">
\theta_n =\theta_n- \alpha\frac{1}{m}\sum_{i=1}^{m}{(h_\theta(x_i) - y_i)x^{(i)}_n}</script><p>这里我们也是假设θ为一个列向量，那么更新之后的θ就等于原来的列向量θ 减去 a/m（实数）<em> （（h(x)(假设函数列向量) - y（数据集y列向量））</em>X（特征值矩阵））</p>
<p>下面是更新theta值的matlab代码：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Theta</span> = <span class="title">UpdateTheta</span><span class="params">(X,Y,theta,alpha)</span></span></span><br><span class="line">    m = <span class="built_in">size</span>(X,<span class="number">1</span>);</span><br><span class="line">    Error = X * theta - Y;</span><br><span class="line">    deta = alpha/m * (X&#x27; * Error);</span><br><span class="line">    Theta = theta - deta;</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>由此可见，使用向量化可以使代码大大减小，相对于之前写的python实现更加简单，并且对于特征值较多的也可以避免使用for循环，使用矩阵运算还可以提高运算速度。</p>
</li>
</ul>

        </div>

        
            <section class="post-copyright">
                
                    <p class="copyright-item">
                        <span>Author:</span>
                        <span><a href="/about/">WD</a></span>
                    </p>
                
                
                    <p class="copyright-item">
                        <span>Permalink:</span>
                        <span><a href="https://did321.gitee.io/2019/07/14/Machine-Learning-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E5%9B%9B-%E2%80%94%E2%80%94Matlab%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/">https://did321.gitee.io/2019/07/14/Machine-Learning-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E5%9B%9B-%E2%80%94%E2%80%94Matlab%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/</a></span>
                    </p>
                
                
                    <p class="copyright-item">
                        <span>License:</span>
                        <span>Copyright (c) 2022 <a target="_blank" rel="noopener" href="http://creativecommons.org/licenses/by-nc/4.0/">CC-BY-NC-4.0</a> LICENSE</span>
                    </p>
                
                
                     <p class="copyright-item">
                         <span>Slogan:</span>
                         <span><a href="#">The blog is my giant.</a></span>
                     </p>
                

            </section>
        
        <section class="post-tags">
            <div>
                <span>Tag(s):</span>
                <span class="tag">
                    
                    
                        <a href="/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"># 机器学习</a>
                    
                        <a href="/tags/Matlab/"># Matlab</a>
                    
                        
                </span>
            </div>
            <div>
                <a href="javascript:window.history.back();">back</a>
                <span>· </span>
                <a href="/">home</a>
            </div>
        </section>
        <section class="post-nav">
            
                <a class="prev" rel="prev" href="/2019/07/16/Machine-Learning-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E4%BA%94-%E2%80%94%E2%80%94Logistic%E5%9B%9E%E5%BD%92/">Machine Learning 学习笔记(五)——Logistic回归</a>
            
            
            <a class="next" rel="next" href="/2019/07/13/Machine-Learning-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E4%B8%89-%E2%80%94%E2%80%94%E5%A4%9A%E5%8F%98%E9%87%8F%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92/">Machine Learning 学习笔记(三)——多变量线性回归</a>
            
        </section>
        <br>
        <br>
    
    <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
    <div id="vcomments"></div>
    <script>
        new Valine({
    el: '#vcomments' ,

    appId: 'JvFy3ebVLo2rUYgHaMweJyXX-MdYXbMMI',
    appKey: 'TCFxfjDAM8UmERPEgYXJmT40',
    serverURLs: 'https://JvFy3ebV.api.lncldglobal.com', 
    placeholder: '----评论区----留下你的评论，作者会定期回复！在昵称处填写QQ号可自动获取邮箱和QQ头像（保护QQ邮箱隐私）',
    enableQQ: true,
    requiredFields: ['nick'],
});
    </script>

    </article>
</div>

        </div>
        <footer id="footer" class="footer">
    <div class="copyright">
        <span>© WD | Powered by <a href="https://hexo.io" target="_blank">Hexo</a> & <a href="https://github.com/Siricee/hexo-theme-Chic" target="_blank">Chic</a></span>
    </div>
</footer>

    </div>
</body>

</html>
